<?php

/**
 * 支付订单回调处理
 * Author: bluer
 * Date: 5/26/16
 */
require LIB_DIR . '/EEOAPI.php';

class OrderProcess {
    private $_platform;
    private $_tradeNo;
    private $_payer;
    private $_orderInfo;

    /**
     * OrderProcess constructor.
     *
     * @param string $outTradeNo 商户订单号
     * @param string $tradeNo 平台交易号
     * @param string $payer 买家账号
     * @param string $paymentMethod 支付方式. bank | alipay | weixin
     */
    public function __construct($outTradeNo, $tradeNo, $payer, $paymentMethod) {
        if (is_string($outTradeNo) || is_int($outTradeNo)) {
            $this->_payer = $payer;
            $this->_tradeNo = $tradeNo;
            $this->_platform = $paymentMethod;
            $this->_orderInfo = $this->_getOrder($outTradeNo);
        }
    }

    protected function _setOrderInfo($orderInfo) {
        $this->_orderInfo = $orderInfo;
    }

    protected function _getOrder($outTradeNo) {
        global $cmsdb;

        return $cmsdb->table($cmsdb->orders)
            ->where('order_id', $outTradeNo)
            ->where('success', 0)
            ->first();
    }

    /**
     * 更新订单状态
     * @return false|int
     */
    protected function _updateOrders() {
        global $cmsdb;

        $param = array(
            'success' => 1,
            'platform_order' => $this->_tradeNo,
            'platform' => $this->_platform,
        );

        if ($this->_platform == 'alipay') {
            $param['alipay_id'] = $this->_payer;
        }

        return $cmsdb->table($cmsdb->orders)
            ->where('order_id', $this->_orderInfo->order_id)
            ->update($param);
    }

    /**
     * 记录用户购买结果
     * @return bool|int 成功返回记录ID,失败返回false
     */
    protected function _insertRelationUserProduct() {
        global $cmsdb;

        $r = [
            'user_id' => $this->_orderInfo->user_id,
            'product_id' => $this->_orderInfo->product_id,
            'order_id' => $this->_orderInfo->order_id,
            'order_time' => $this->_orderInfo->create_time,
            'product_type' => $this->_orderInfo->product_type
        ];

        if ($this->_orderInfo->channel == 'dashang') {
            $r['channel'] = 9; //微信打赏
        }

        $result = $cmsdb->table($cmsdb->userProductR)->insert($r);

        if ($result) return $cmsdb->lastInsertId();

        return $result;
    }

    /**
     * 记录用户快递信息
     * @param int $rupId
     * @return bool
     */
    protected function _insertExpress($rupId) {
        global $cmsdb;

        return $cmsdb->table($cmsdb->expressTasks)
            ->insert(array(
                'rup_id' => $rupId,
                'user_id' => $this->_orderInfo->user_id,
                'express_num' => '',
                'express_type' => '',
                'create_time' => date('Y-m-d H:i:s'),
                'status' => 0,
                'course_id' => $this->_orderInfo->product_id,
                'batch_no' => '',
                'available' => 1
            ));
    }

    /**
     * 记录用户使用的订单邀请码
     * @param $cashbackFee
     * @return bool
     */
    protected function _insertOrderInvites($cashbackFee) {
        global $cmsdb;

        return $cmsdb->table($cmsdb->orderInvites)
            ->insert(array(
                'invite_user_id' => $this->_orderInfo->invite_user_id,
                'user_id' => $this->_orderInfo->user_id,
                'order_id' => $this->_orderInfo->order_id,
                'course_id' => $this->_orderInfo->product_id,
                'order_time' => $this->_orderInfo->create_time,
                'cashback_fee' => intval($cashbackFee),
                'status' => 2
            ));
    }

    public function getOrder() {
        return $this->_orderInfo;
    }

    /**
     * 检查订单是否存在
     * @return bool
     */
    public function isExists() {
        return is_object($this->_orderInfo);
    }

    /**
     * 检测用户购买情况
     *
     * @return string|false
     */
    public function isPurchased() {
        global $cmsdb;

        return $cmsdb->table($cmsdb->userProductR)
            ->where('user_id', $this->_orderInfo->user_id)
            ->where('product_id', $this->_orderInfo->product_id)
            ->where('product_type', $this->_orderInfo->product_type)
            ->value('id');
    }

    /**
     * 完成订单
     *
     * @return bool
     */
    public function finish() {
        global $cmsdb;

        if (!$this->isExists()) return false;

        $cmsdb->beginTransaction();

        $rs1 = $this->_updateOrders();
        $rs2 = $this->_insertRelationUserProduct();

        $rs3 = true;
        $rs4 = true;
        if (!$this->_orderInfo->is_for_scramble) {
            if ($this->_orderInfo->has_express && $rs2) {
                $rs3 = $this->_insertExpress($rs2);
            }

            //邀请码使用记录
            if ($this->_orderInfo->invite_user_id) {
                $cashbackFee = $cmsdb->table($cmsdb->liveCourses)
                    ->where('id', $this->_orderInfo->product_id)
                    ->value('cashback_fee');

                if (!empty($cashbackFee)) $rs4 = $this->_insertOrderInvites($cashbackFee);
            }
        }

        //事务结果验证
        if ($rs1 === false || $rs2 === false || $rs3 === false || $rs4 === false) {
            $cmsdb->cancelTransaction(); //rollback
            return false;
        }

        $cmsdb->endTransaction(); //commit

        // 更新用户的支付宝账号
        if (!empty($this->_payer)) $this->updatePayerInfo($this->_payer, 'alipay');

        if ($this->_orderInfo->product_type == 'zhiboke') {
            //更新购课人数缓存
            updateCoursePurchasedPersons($this->_orderInfo->product_id, 1);

            //eeo课程处理
            if (!$this->_orderInfo->is_for_scramble) {
                $this->enrollEEOCourse($this->_orderInfo->product_id, $this->_orderInfo->user_id);
            }
        }

        return true;
    }

    /**
     * 更新付款人信息
     * @param string $str 付款人ID
     * @param string $platform  alipay | weixin
     * @return false|int
     */
    public function updatePayerInfo($str, $platform) {
        global $uddb;

        if ($platform == 'alipay') {
            return $uddb->table($uddb->userSocialInfo)
                ->where('user_id', $this->_orderInfo->user_id)
                ->update('alipay_id', $str);
        }

        return false;
    }

    /**
     * 开通eeo课程
     *
     * @param int $courseId 课程id
     * @param int $userId 用户id
     * @return bool
     */
    public function enrollEEOCourse($courseId, $userId) {
        global $cmsdb, $uddb;

        $eeoCourseId = $cmsdb->table($cmsdb->liveCourses)
            ->where('id', $courseId)
            ->value('eeo_course_id');
        if (empty($eeoCourseId)) return false;

        $phone = $uddb->table($uddb->userAuthInfo)
            ->where('ID', $userId)
            ->value('phone');
        if (empty($phone)) return false;

        $nickname = $uddb->table($uddb->userSocialInfo)
            ->where('user_id', $userId)
            ->value('nickname');

        $eeo = new EEO();
        if ($eeo->addCourseStudent($eeoCourseId, $phone, empty($nickname) ? $phone : $nickname, false)) {

            //进入EEO测试名单
            $uddb->insert('eeo_client_test', [
                'user_id' => $userId,
                'course_id' => $courseId,
                'create_time' => date('Y-m-d H:i:s'),
                'retest' => 0,
                'status' => 0,
                'qqgroup_status' => 0
            ]);

            return true;
        }

        return false;
    }

    /**
     * 清除订单信息缓存
     * @param $outTradeNo
     * @return bool
     */
    static function clearCache($outTradeNo) {
        $cacheKey = 'orderInfo:' . $outTradeNo;
        return cacheDelete($cacheKey);
    }
}